//
//  ImageLoader.m
//  WeddingStoreFinder
//
//  Created by Macdev on 11/19/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageLoader.h"


static ImageLoader *instance;

@implementation ImageLoader

@synthesize delegate, imgURL, image, imageData, needRespondInUIThread;
@synthesize imageName;


#pragma mark - Singleton methods

+ (ImageLoader*) getInstacne {
	if (!instance) {
		instance = [[ImageLoader alloc] init];
	}
	return instance;
}

+ (void) releaseInstance {
	if (instance) {
		[instance release];
	}
}

-(id) init {
    self = [super init];
    if (self) {
        needRespondInUIThread = YES;
    }
    return self;
}



#pragma mark -
#pragma mark Instance methods

- (BOOL) imageLoaded {
    if (image) {
        return YES;
    }
    
	if (imageName) {
		self.imgURL = [NSString stringWithFormat:@"%@/%@", kImageDownloadBaseUrl, imageName];
		
		NSOperationQueue *queue = [[NSOperationQueue alloc] init];
		NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
											initWithTarget:self
											selector:@selector(loadImage) 
											object:nil];
		[queue addOperation:operation]; 
		[operation release];
		[queue release];
		return NO;
	}
	if (needRespondInUIThread) {
		[self.delegate performSelectorOnMainThread:@selector(noImageFound:) withObject:self waitUntilDone:NO];
	} else {
		[self.delegate noImageFound:self];
	}	

    return NO;
}

- (void) loadImage {
	NSData *imageData_ = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgURL]];
	UIImage *imgT = [[UIImage alloc] initWithData:imageData_];
    
    self.image = imgT;
	self.imageData = imageData_;
    [imgT release];
	if (self.delegate) {
		if ([imageData_ length] > 0) {
			if (needRespondInUIThread) {
				[self.delegate performSelectorOnMainThread:@selector(imageDidLoad:) withObject:self waitUntilDone:NO];
			} else {
				[self.delegate imageDidLoad:self];
			}
		} else {
			if (needRespondInUIThread) {
				[self.delegate performSelectorOnMainThread:@selector(noImageFound:) withObject:self waitUntilDone:NO];
			} else {
				[self.delegate noImageFound:self];
			}
			
		}
	}
	
    [imageData_ release];
    
}




#pragma mark -
#pragma mark Memory management

- (void) dealloc {
    [imgURL release];
    [image release];
	[imageData release];
	[imageName release];
    
    [super dealloc];
}







@end
